<template>
  <div class="home-page">
    <page-header>
      <!-- 高保真设计中没有缩放按钮 -->
      <!-- <template slot="header-left">
        <app-button radius="0px" type="primary" class="system-item app-text-inverse-color__text"
          @click="collapse = !collapse">
          <i class="app-font-size24" :class="collapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"></i>
        </app-button>
      </template> -->
      <template slot="header-right" v-if="userInfo">
        <!-- <el-avatar :src="userInfo.avatar"></el-avatar> -->
        <el-dropdown class="home-page__user-info" trigger="click" @command="headerClick"
          @visible-change="visibleDropdown">
          <span class="home-page__drop-link app-text-inverse-color__text all-animation">
            {{ userInfo.userName }}<i
              :class="['el-icon-arrow-down el-icon--right all-animation', expand ? 'expand' : '']"></i>
          </span>
          <el-dropdown-menu>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </page-header>
    <div class="flex-auto flex-row no-overflow">
      <left-menu :collapse="collapse"></left-menu>
      <div class="flex-auto flex-column no-overflow">
        <page-breadcrumb></page-breadcrumb>
        <div class="flex-auto no-overflow">
          <!-- HOME页面作为一个空页面，主要用于承载所有子页面，该页面不展示任何内容，用于做页面跳转 -->
          <keep-alive :include="cachedViews">
            <router-view class="main-router-view" :key="$route.fullPath"></router-view>
          </keep-alive>
        </div>
      </div>
    </div>
    <changePassword ref="changePassword" @success="updateSuccess"></changePassword>
  </div>
</template>

<script>
import pageHeader from '@/components/business/page-layout/page-header/page-header';
import leftMenu from '@/components/business/page-layout/left-menu/left-menu';
import pageBreadcrumb from '@/components/business/page-layout/page-breadcrumb/page-breadcrumb';
import api from '../api/index.js';
import changePassword from '../components/change-password.vue';
const loginPage = window.systemConfig.LOGIN_PAGE;
const homePage = window.systemConfig.HOME_PAGE;
export default {
  name: 'HomePage',
  components: {
    pageHeader,
    leftMenu,
    pageBreadcrumb,
    changePassword
  },
  data() {
    return {
      cachedViews: [],
      collapse: false,
      expand: false,
    };
  },
  computed: {
    userToken() {
      return this.$store.getters.userToken;
    },
    userInfo() {
      return this.$store.getters.userInfo;
    }
  },
  beforeDestroy() { },
  created() {
    // 如果用户未登录，则跳转至登录页面
    if (!this.userToken || !this.userToken.length) {
      this.$log.debug('用户未登录，退出至登录页面：', loginPage);
      this.$router.replace({
        path: loginPage
      });
    } else {
      this.getUserInfo();
    }
  },
  methods: {
    getUserInfo() {
      api.getUserInfo().then((res) => {
        if (res.success && res.data) {
          const userInfo = res.data;
          this.$log.debug('用户信息获取成功，用户信息为：', userInfo);
          this.$store.commit(this.$cacheKeys.CACHE_USER_INFO, userInfo);
          this.initMenu();
        } else {
          this.$log.error('用户信息获取失败，错误信息为：', res.message);
          // 如果接口响应码是407，则表示用户token过期，需要重新登录
          if (res.status === 407) {
            this.$message.error('用户会话过期，请重新登录');
            this.$store.dispatch('clearUserInfo');
            this.$router.replace({
              path: loginPage
            });
            return;
          }
          this.$message.error('获取用户信息失败：' + (res.message || ''));
        }
      }).catch(e => {
        this.$log.error('用户信息获取失败，错误信息为：', e);
      });
    },
    initMenu() {
      const systemMenu = this.$utils.filterTreeByRole(this.$config.SYSTEM_MENU, this.userInfo.roleName, 'roles', 'children');
      this.$store.commit(this.$cacheKeys.CACHE_SYSTEM_MENU, systemMenu);
      const menuList = this.$utils.flattenTreeWithParentId(systemMenu, 'index', 'children');
      this.$store.commit(this.$cacheKeys.CACHE_SYSTEM_MENU_ARRAY, menuList);
      const currentPath = this.$route.path;
      const currentNode = this.$utils.findBreadcrumbByPath(systemMenu, currentPath, 'path', 'children');
      // 登录成功后，找到第一个页面路由，跳转至第一个路由地址
      // 如果当前页面是首页，或者当前页面在菜单列表中已经不存在，则跳转至菜单中的第一个页面
      if (currentPath === homePage || !currentNode || !currentNode.length) {
        const firstNode = this.$utils.findFirstNode(systemMenu);
        let firstPage = '/common/dashboard/dashboard';
        if (firstNode) {
          firstPage = firstNode.path;
        }
        this.$router.replace({
          path: firstPage
        });
      }
    },
    visibleDropdown(e) {
      this.expand = e;
    },
    headerClick(command) {
      this.$log.debug('用户点击【' + command + '】按钮操作');
      switch (command) {
        case 'logout':
          this.$confirm('确定退出登录？', '退出登录', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then((res) => {
              if (res === 'confirm') {
                this.$log.debug('用户点击退出登录，即将退出至登录页面');
                api.userLogout().then((res) => {
                  if (res.success) {
                    this.$log.info('用户退出登录成功：', res);
                  } else {
                    this.$log.error('用户退出登录失败，错误信息：', res);
                  }
                  this.$message.success('用户退出登录成功');
                  this.$store.dispatch('clearUserInfo');
                  this.$router.replace({
                    path: loginPage
                  });
                }).catch((e) => {
                  // 不管成功与否，都将退出登录
                  this.$message.success('用户退出登录成功');
                  this.$store.dispatch('clearUserInfo');
                  this.$router.replace({
                    path: loginPage
                  });
                  this.$log.error('用户退出登录失败，错误信息：', e);
                });
              }
            })
            .catch(() => {
              this.$log.debug('用户取消退出登录');
            });
          break;
        case 'changePassword':
          this.$refs['changePassword'].open();
          break;
      }
    },
    updateSuccess() {
      this.$confirm("当前账号密码已修改，点击重新登录返回到登录页面", "提示", {
        confirmButtonText: "重新登录",
        showCancelButton: false,
        showClose: false,
        closeOnClickModal: false,
        type: "warning",
      }).then(() => {
        api.userLogout().then((res) => {
          if (res.success) {
            this.$store.dispatch('clearUserInfo');
            this.$router.replace({
              path: loginPage
            });
          } else {
            this.$log.error('用户退出登录失败，错误信息：', res);
            // 用户退出登录失败，也清空用户信息，退出到登录页面
            this.$store.dispatch('clearUserInfo');
            this.$router.replace({
              path: loginPage
            });
          }
        }).catch((e) => {
          this.$log.error('用户退出登录失败，错误信息：', e);
          // 用户退出登录失败，也清空用户信息，退出到登录页面
          this.$store.dispatch('clearUserInfo');
          this.$router.replace({
            path: loginPage
          });
        });
      }).catch(() => { });
    }
  }
};
</script>

<style lang="scss" scoped>
@import '@/business/style/mixin.scss';

.home-page {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  &__user-info {
    margin-left: 15px;
  }

  &__drop-link {
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 20px;

    &:hover {
      background-color: #f9f9f9;
      @include set_theme_style(color, app-primary-color);
    }

    i.expand {
      transform: rotate(-180deg);
    }
  }

  .system-item {
    height: 64px;
    width: 64px;
    line-height: 64px;
    text-align: center;
    cursor: pointer;
  }
}
</style>